// Copyright 2000-2024 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.linqingying.gitcode.pullrequest.data

import com.intellij.collaboration.ui.icon.AsyncImageIconsProvider
import com.intellij.platform.util.coroutines.childScope
import kotlinx.coroutines.*
import com.linqingying.gitcode.api.GitCodeApiRequestExecutor
import com.linqingying.gitcode.api.GitCodeApiRequests
import com.linqingying.gitcode.api.GitCodeServerPath
import com.linqingying.gitcode.api.data.GCReactionContent
import com.linqingying.gitcode.api.executeSuspend
import java.awt.Image

internal class GCReactionImageLoader(
  parentCs: CoroutineScope,
  private val serverPath: GitCodeServerPath,
  private val requestExecutor: GitCodeApiRequestExecutor
) : AsyncImageIconsProvider.AsyncImageLoader<GCReactionContent> {
  private val cs = parentCs.childScope(CoroutineName("GitCode Reactions Image Loader"))

  private val emojisNameToUrl: Deferred<Map<String, String>> = cs.async(Dispatchers.IO) {
    requestExecutor.executeSuspend(GitCodeApiRequests.Emojis.loadNameToUrlMap(serverPath))
  }

  override suspend fun load(key: GCReactionContent): Image? {
    val map = emojisNameToUrl.await()
    val url = map[key.emojiName] ?: return null
    return withContext(Dispatchers.IO) {
      // seems to be a bug in gitcode asset manager - loading emoji images with auth sometimes leads to 404
      val exec = if (url.contains("gitcodeassets")) GitCodeApiRequestExecutor.Factory.getInstance().create() else requestExecutor
      return@withContext exec.executeSuspend(GitCodeApiRequests.Emojis.loadImage(url))
    }
  }
}

private val GCReactionContent.emojiName: String
  get() = when (this) {
    GCReactionContent.THUMBS_UP -> "+1"
    GCReactionContent.THUMBS_DOWN -> "-1"
    GCReactionContent.LAUGC -> "smile"
    GCReactionContent.HOORAY -> "tada"
    GCReactionContent.CONFUSED -> "confused"
    GCReactionContent.HEART -> "heart"
    GCReactionContent.ROCKET -> "rocket"
    GCReactionContent.EYES -> "eyes"
  }
